#include <iostream>
#include <cstdio>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void ChildWrite(int fd){
    char buffer[1024] = {0};
    int cnt = 10;
    const char* msg = "child write data";
    while(cnt--){
        snprintf(buffer, sizeof(buffer), "%s", msg);
        write(fd, buffer, sizeof(buffer)-1);
    }
}

void FatherRead(int fd){
    char buffer[1024] = {0};
    int cnt = 10;
    while(cnt--){
        buffer[0] = 0; //清空buffer
        read(fd, buffer, sizeof(buffer)-1);
        std::cout << "father read: " << buffer <<"num is " << cnt << std::endl;
        sleep(1);
    }
}

int main(){
    //1、创建管道
    int fds[2] = {0};
    int n = pipe(fds);
    if(n < 0){
        std::cerr << "pipe error" << std::endl;
        exit(1);
    }
    std::cout<<fds[0]<<" "<<std::endl;
    std::cout<<fds[1]<<" "<<std::endl;

    //2、创建子进程
    int pid = fork();
    if(pid == 0){
        //子进程
        close(fds[0]); //关闭读端
        ChildWrite(fds[1]);
        close(fds[1]); //关闭写端
        exit(0);
    }

    //父进程
    close(fds[1]);
    FatherRead(fds[0]);
    close(fds[0]);

    return 0;
}